package com.leyou.service.turn;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leyou.api.TurnService;
import com.leyou.constant.DefineException;
import com.leyou.dao.db1.Db1Mapper;
import com.leyou.dao.db2.Db2Mapper;
import com.leyou.domain.db1entity.ConditionAndGoods;
import com.leyou.domain.db1entity.TableCell;
import com.leyou.domain.db1entity.TurnTableRecord;
import com.leyou.domain.db3entity.LeyouCoupons;
import com.leyou.domain.db3entity.Prscard;
import com.leyou.domain.vo.StartTurnVO;
import com.leyou.domain.vo.TurnRecordVO;
import com.leyou.domain.vo.TurnTableActivityInfoVO;
import com.leyou.utils.HttpRequest;
import com.leyou.utils.Utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lixin
 * @Date 2018/11/21 18:00
 * @Version 1.0
 * @Description TODO
 **/
@Service
public class TurnServiceImp implements TurnService {


    @Autowired
    Db1Mapper db1Mapper;

    @Autowired
    Db2Mapper db2Mapper;

    @Autowired
    RabbitTemplate rabbitTemplate;


    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public TurnTableActivityInfoVO getTurnTableActivityInfoVO(String activityKey) {
        return db1Mapper.getTurnTableActivityInfoVO(activityKey);
    }

    @Override
    public String getCardNumByUserId(String userId) {
        return db2Mapper.getCardNumByUserId(userId);
    }

    @Override
    public boolean isPrizeAvaiable(TableCell tableCell, String activityKey) {

        Integer turnTableRecordCount = db1Mapper.getTurnTableRecordCount(tableCell, activityKey);

        if (tableCell.getMaxGet() > turnTableRecordCount) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public TableCell getAvailableTableCell(String activityKey) {
        return db1Mapper.getAvailableTableCell(activityKey);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void sendPrize(TableCell prize, StartTurnVO startTurnVO, String cardNum, TurnTableActivityInfoVO turnTableActivityInfoVO) throws RuntimeException {

        switch (prize.getCelltype()) {
            case "1":
                //优惠券奖品
                LeyouCoupons leyouCoupons = new LeyouCoupons();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date begintime = null;
                Date endtime = null;
                if (StringUtils.isBlank(prize.getEndType())) {
                    throw new DefineException(400000, "优惠券奖品结束时间类型为空");
                }
                switch (prize.getEndType()) {
                    case "1":
                        //优惠券固定结束时间
                        begintime = new Date();
                        endtime = prize.getDeadline();
                        break;
                    case "2":
                        //优惠券固定持续时间
                        begintime = new Date();
                        endtime = Utils.getDateAfter(new Date(), prize.getDuration());
                        break;
                    default:
                        throw new DefineException(400000, "优惠券结束类型错误");
                }
                leyouCoupons.setStarttime(begintime);
                leyouCoupons.setEndtime(endtime);
                leyouCoupons.setValue(prize.getQuota());
                leyouCoupons.setStatus("0");
                leyouCoupons.setCardnum(String.valueOf(cardNum));
                leyouCoupons.setType(Integer.valueOf(prize.getCouponkey()));
                leyouCoupons.setNumberCode(String.valueOf(System.currentTimeMillis()));
                leyouCoupons.setUserId(Integer.parseInt(startTurnVO.getUserId()));
                db2Mapper.sendLeyouCoupons(leyouCoupons);
                break;
            case "2":
                //积分奖品
                //发积分
                System.out.println(startTurnVO.getUserId());
                db2Mapper.addUserPonits(startTurnVO.getUserId() + "", prize.getQuota());
                break;
            case "3":
                //实物奖品
                break;
            case "4":
                //谢谢惠顾奖品
                break;
            default:
                throw new DefineException(400000, "无次奖品类型" + prize.getCelltype());
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void putTableRecord(TurnRecordVO turnRecordVO) {
        TurnTableRecord turnTableRecord = new TurnTableRecord();
        turnTableRecord.setRecordkey(Utils.getUUID(32));
        TableCell tableCell = turnRecordVO.getTableCell();
        turnTableRecord.setUserkey(String.valueOf(turnRecordVO.getUserId()));
        turnTableRecord.setCardkey(String.valueOf(turnRecordVO.getCardNum()));
        turnTableRecord.setActivitykey(tableCell.getActivitykey());
        turnTableRecord.setPrizetype(tableCell.getCelltype());
        turnTableRecord.setCouponkey(tableCell.getCouponkey());
        turnTableRecord.setPointcount(tableCell.getQuota());
        turnTableRecord.setGoosname(tableCell.getGoodsname());
        turnTableRecord.setTableCellKey(tableCell.getCellkey());
        turnTableRecord.setReceiveTime(new Date());

        //生成记录
        db1Mapper.putTableRecord(turnTableRecord);

        //削减奖品数量
        if (turnRecordVO.getTableCell().getTotal() != null && turnRecordVO.getTableCell().getTotal() != 0) {
            db1Mapper.updateTableCell(turnRecordVO.getTableCell());
        }

    }

    @Override
    public int getTotalCostInItemListByUserId(TurnTableActivityInfoVO turnTableActivityInfoVO, Integer userId) {
        List<ConditionAndGoods> conditionAndGoodsList = turnTableActivityInfoVO.getConditionPutVO().getConditionAndGoodsList();

        Integer totalCostInItemListByUserId = db2Mapper.getTotalCostInItemListByUserId(conditionAndGoodsList, userId, conditionAndGoodsList.get(0).getBegintime(), conditionAndGoodsList.get(0).getEndtime());

        if (totalCostInItemListByUserId == null) {
            return 0;
        } else {
            return totalCostInItemListByUserId;
        }
    }

    @Override
    public int getActivityTryCountByUserId(StartTurnVO startTurnVO) {
        return db1Mapper.getActivityTryCountByUserId(startTurnVO);
    }

    @Override
    public Prscard selectUser(String username, String password) {
        return db2Mapper.selectUser(username, password);
    }
}
